package com.bdd.service.impl;

import com.bdd.common.AjaxResponseResult;
import com.bdd.common.IdentityStatus;
import com.bdd.dao.UserDao;
import com.bdd.dto.ContactDto;
import com.bdd.dto.IdentityDto;
import com.bdd.dto.QueryDto;
import com.bdd.dto.UserDto;
import com.bdd.entities.User;
import com.bdd.service.ContactFeignService;
import com.bdd.service.IdentityFeignService;
import com.bdd.service.UserService;
import com.bdd.vo.PageVo;
import com.bdd.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author Bdd
 * @Description
 * @Date 2020/3/23 19:33
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    @Resource
    private IdentityFeignService identityFeignService;

    @Resource
    private ContactFeignService contactFeignService;

    /**
     * 保存信息
     * @param userDto
     * @return
     */
    @Override
    public AjaxResponseResult<UserVo> save(UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        System.out.println(user);

        user.setIdentityStatus(IdentityStatus.UNAUTHORIZED.getStatus());
        userDao.saveUser(user);
//        user.setId(userDao.saveUser(user));
        if(user.getId() != 0 || user.getId() != null) {
            //同步处理identity
            IdentityDto identityDto = new IdentityDto();
            identityDto.setId(user.getId());
            BeanUtils.copyProperties(userDto,identityDto);
            identityFeignService.save(identityDto);

            //同步处理Contact
            ContactDto contactDto = new ContactDto();
            contactDto.setId(user.getId());
            BeanUtils.copyProperties(userDto,contactDto);
            contactFeignService.save(contactDto);

            return new AjaxResponseResult<>(200, "创建成功");
        }
        return new AjaxResponseResult<>(400,"创建失败");
    }

    /**
     * 更改认证信息
     * @param id
     * @return
     */
    @Override
    public AjaxResponseResult auth(Long id) {
        int result = userDao.auth(id, IdentityStatus.AUTHENTICATED.getStatus());
        if(result > 0)
            return new AjaxResponseResult(200,"认证成功");
        return new AjaxResponseResult(400,"认证失败");
    }

    /**
     * 分页
     * @param queryDto
     * @return
     */
    @Override
    public AjaxResponseResult page(QueryDto queryDto) {
        PageVo pageVo = new PageVo(queryDto.getPageNum(),totals(queryDto),queryDto.getSize());
        int index = queryDto.getPageNum() - 1;
        queryDto.setPageNum(index < 0 ? 0 : index);
        pageVo.setData(userDao.page(queryDto));
        return new AjaxResponseResult(200,"查看成功",pageVo);
    }

    private int totals(QueryDto queryDto){
        int result = userDao.pageTotals(queryDto);
        return result;
    }
}
